package saintseiya.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFileChooser;

import saintseiya.view.MainFrame;

public class CmpsCompress {

	/**
	 * @param  args
	 * @throws IOException
	 * @throws Exception
	 */
	public static void main(String[] args) throws IOException {
		// initialize properties with default value
		Properties props = new Properties();
		props.setProperty(MainFrame.LAST_DIR_KEY, MainFrame.DEFAULT_LAST_DIR);
		// try to load values from file
		try {
			props.load(new FileReader(MainFrame.PROP_FILE));
		}
		catch(IOException ioe) {}

		// file chooser to choose the folder or file
		JFileChooser chooser = new JFileChooser();
		chooser.setDialogTitle("Select file to compress");
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setCurrentDirectory(new File(props.getProperty(MainFrame.LAST_DIR_KEY)));
		int returnVal = chooser.showOpenDialog(null);

		// if file was selected
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File selectedFile = chooser.getSelectedFile();
			// check validity
			if (selectedFile.exists() && selectedFile.canRead() && selectedFile.isFile()) {
				// update the properties file
				props.setProperty(MainFrame.LAST_DIR_KEY, selectedFile.getParentFile().getAbsolutePath());
				props.store(new FileWriter(MainFrame.PROP_FILE), null);

				compress(selectedFile);
			}
		}
	}

	private static void compress(File file) throws IOException {

		DataOutputStream dos = new DataOutputStream(new FileOutputStream( new File(file.getParent(), file.getName()) + "_" ));
		DataInputStream dis = new DataInputStream(new FileInputStream(file));

		dos.write('C');
		dos.write('M');
		dos.write('P');
		dos.write('S');
		dos.write(1);
		dos.write(0);
		dos.write(0);
		dos.write(0);
		dos.writeInt( Integer.reverseBytes((int)file.length()) );
		dos.write(0);
		dos.write(0);
		dos.write(0);
		dos.write(0);

		int count = 0;
		int b;
		while( (b = dis.read()) != -1 ) {
			if(++count % 8 == 1) {
				dos.write(255);
			}
			dos.write(b);
		}

		dis.close();
		dos.flush();
		dos.close();
	}
}